package com.example.administrator.handletest;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private Button startbtn ,stopbtn;
    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startbtn = (Button) findViewById(R.id.btn1);
        startbtn.setOnClickListener(new StartButtonListen());
        stopbtn = (Button) findViewById(R.id.btn2);
        stopbtn.setOnClickListener(new StopButtonListener());
    }


    //1.创建一个Handler对象.
    Handler handler = new Handler();
    private class StartButtonListen implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            //2.调用Handler的post方法，将要执行的线程对象添加到队列当中，同样下面也有停止按钮
            handler.post(updateThread);
        }
    }

    private class StopButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {

            handler.removeCallbacks(updateThread);
        }
    }

    Runnable updateThread = new Runnable() {
        @Override
        public void run() {
            System.out.println("UpdateThread");
            Log.v("tag","UpdateThread");

            handler.postDelayed(updateThread,2000);
        }
    };
}
